class UserController < ApplicationController
  include ActionView::Helpers::NumberHelper
  def do_login
    require "net/https"
    require 'json'
    require "uri"
    data = 'error'
    session[:user] = nil
    session[:user_data] = nil
    if !params[:uid].empty?
      begin
        url = "https://graph.facebook.com/#{params[:uid]}"
        uri = URI.parse(url)
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        request = Net::HTTP::Get.new(uri.request_uri)
        response = http.request(request)
        data = response.body
        result = JSON.parse(data)
        session[:user_data] = result
      rescue Timeout::Error
      rescue
      end
      @user = nil
      @user = User.find(:first, :conditions=>["uid=?", params[:uid]])
      if !@user
        @user = User.new
        @user.uid = params[:uid]
        @user.save
      end
      session[:user] = @user
    end
    if session[:user]
      redirect_to :action=>"index"
    else
      redirect_to :controller=>"welcome", :action=>"index"
    end
  end

  def do_normal_login
    user = User.find(:first, :conditions=>["username=? AND password=? AND u_status='Active'",params[:username],params[:password]])
    if user
      session[:user] = user
      session[:user_normal] = "#{user.firstname} #{user.lastname}"
      redirect_to :action=>"index"
    else
      redirect_to :controller=>"welcome", :action=>"index"
    end
  end

  def index
    render :action=>"index", :layout=>"basic_layout"
  end

  def logout
    session[:user] = nil
    session[:user_data] = nil
    session[:user_normal] = nil
    session[:player] = nil
    redirect_to :controller=>"welcome", :action=>"index"
  end

  def joingame
    @word = ''
    if params[:word]
      @word = params[:word]
    end
    render :action=>"joingame", :layout=>"basic_layout"
  end

  def findgame
    player = Player.find(:first, :conditions=>["gencode=?", params[:gencode]])
    if player
      session[:player] = player
      if session[:user]
        game_history = GameHistory.find(:first, :conditions=>["player_id=? AND user_id=?", player.id, session[:user].id])
        if !game_history
          game_history = GameHistory.new
          game_history.user_id = session[:user].id
          game_history.player_id = player.id
          game_history.save
        end
      end
      if player.player_type=="B"
        redirect_to :action=>"plan_game"
      else
        redirect_to :action=>"plan_game_a"
      end
    else
      redirect_to :action=>"joingame", :word=>"ไม่พบห้องที่ระบุ"
    end
  end

  def foundgame
    @word = ''
    if params[:word]
      @word = params[:word]
    end
    if session[:player]
      if session[:player].player_type=="A"
        render :text=>"You do not have goods for sell in this market.", :layout=>"basic_layout"
      else
        render :action=>"foundgame", :layout=>"basic_layout"
      end
    else
      render :action=>"foundgame", :layout=>"basic_layout"
    end
  end

  def save_custom
    player = Player.find(session[:player].id)
    player.custom_name = params[:custom_name]
    player.save
    session[:player] = player
    redirect_to :action=>"foundgame", :word=>"Saved! #{Time.now}"
  end

  def rungame
    @games = Game.find(:all, :conditions=>["user_id=?",session[:user].id], :order=>"id desc")
    render :action=>"rungame", :layout=>"basic_layout"
  end

  def save_inventory
    word = ''
    game = Game.find(session[:player].game_id)
    player = Player.find(:first, :conditions=>["id=?", session[:player].id])
    if game.edit_inventory=="Y"
      player.remain_inventory = params[:inventory]
      player.save
      session[:player] = player
      word = "Saved #{Time.now}"
    else
      word = "Cannot Save, Session Locked!"
    end
    redirect_to :action=>"foundgame", :word=>word
  end

  def save_price
    word = ''
    game = Game.find(session[:player].game_id)
    player = Player.find(:first, :conditions=>["id=?", session[:player].id])
    if game.run_flag=="Y"
      player.price = params[:price]
      player.year = game.current_year
      player.round = game.current_round
      player.save
      session[:player] = player
      word = "Saved #{Time.now}"
    else
      word = "Cannot Save, Session Locked!"
    end
    redirect_to :action=>"foundgame", :word=>word
  end

  def save_promotion
    word = ''
    game = Game.find(session[:player].game_id)
    player = Player.find(:first, :conditions=>["id=?", session[:player].id])
    if game.run_flag=="Y"
      promotion = ((number_with_precision(params[:promotion], :precision=>2)).to_f * 1000000).to_i
      player.promotion = promotion
      player.save
      session[:player] = player
      word = "Saved #{Time.now}"
    else
      word = "Cannot Save, Session Locked!"
    end
    redirect_to :action=>"foundgame", :word=>word
  end

  def roll_share
    word = "It's not Your Turn."
    game = Game.find(session[:player].game_id)
    game_setting = game.game_setting
    player = Player.find(:first, :conditions=>["id=?", session[:player].id])
    sale = Sale.find(:first, :conditions=>["game_id=? AND year=? AND round=? AND player_id=?", game.id, game.current_year, game.current_round, session[:player].id])
    if sale
      if sale.sold_flag=='Y'
        sold = 0
        market_remain = game.market_remain
        player_remain = player.remain_inventory
        min_sold = (game.min_sold * 100).to_i
        max_sold = (game.max_sold * 100).to_i
        ext_sold = 0
        if game_setting.step_flag=='Y'
          step_remain = game_setting.step_remain
          if step_remain<0
            step_remain = 0
          end
          ext_sold = (game_setting.step_size * step_remain * 100).to_i
        end
        upper = rand(max_sold-min_sold+1)+min_sold+ext_sold
        if upper>100
          upper = 100
        end
        presold = upper * player_remain/100.0
        sold = (presold/10000.0).round * 10000
        if sold>player_remain
          sold = player_remain
        end
        if sold>market_remain
          sold = market_remain
        end
        sale.quantity = sold
        sale.cash = sold * (sale.price + sale.price_added)
        sale.sold_flag = 'N'
        sale.save

        player.remain_inventory = player_remain - sold
        player.save
        session[:player] = player

        game.market_remain = game.market_remain - sold
        game.save
        word = "Done! #{Time.now}"

        #game_setting.total_q = game_setting.total_q + sold
        #game_setting.total_mul = game_setting.total_mul + (game_setting.last_price * sold)
        #game_setting.average_price = (game_setting.total_mul.to_f / game_setting.total_q).round(2)
        #game_setting.save
        if game_setting.step_remain>0
          game_setting.step_remain = game_setting.step_remain - 1
          game_setting.save
        end
      else
        word = "It's not Your Turn."
      end
    end
    redirect_to :action=>"foundgame", :word=>word
  end

  def plan_game
    @word = ''
    if params[:word]
      @word = params[:word]
    end
    if session[:player]
      if session[:player].player_type=="A"
        redirect_to :action=>"plan_game_a", :word=>@word
      else
        render :action=>"plan_game", :layout=>"basic_layout"
      end
    else
      render :action=>"plan_game", :layout=>"basic_layout"
    end
  end

  def plan_game_a
    @word = ''
    if params[:word]
      @word = params[:word]
    end
    if session[:player]
      if session[:player].player_type=="B"
        redirect_to :action=>"plan_game"
      else
        render :action=>"plan_game_a", :layout=>"basic_layout"
      end
    else
      render :action=>"plan_game_a", :layout=>"basic_layout"
    end
  end

  def show_board_bk
    @player = Player.find(:first, :conditions=>["gencode=?", params[:id]])
    @year = params[:year].to_i
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    @pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @debts = Debt.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @debts_value = Debt.sum(:amount, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @factories = Factory.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @factories_value = Factory.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    @warehouses = Warehouse.find(:all, :conditions=>["player_id=? AND year<=?", @player.id, @year], :order=>"id")
    @warehouses_value = Warehouse.sum(:remain_value, :conditions=>["player_id=? AND year<=?", @player.id, @year])
    render :action=>"show_board", :layout=>"basic_noheader_layout"
  end

  def show_board
    @player = Player.find(:first, :conditions=>["gencode=?", params[:id]])
    @year = params[:year].to_i
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    board = Board.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @data = board.board_data
    render :action=>"show_board", :layout=>"basic_noheader_layout"
  end

  def show_balance_sheet
    @player = Player.find(:first, :conditions=>["gencode=?", params[:id]])
    @year = params[:year].to_i
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    board = Board.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @data = board.balance_sheet
    render :action=>"show_balance_sheet", :layout=>"basic_noheader_layout"
  end

  def show_income_statement
    @player = Player.find(:first, :conditions=>["gencode=?", params[:id]])
    @year = params[:year].to_i
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    board = Board.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @data = board.income_statement
    render :action=>"show_income_statement", :layout=>"basic_noheader_layout"
  end

  def show_cash_flow_statement
    @player = Player.find(:first, :conditions=>["gencode=?", params[:id]])
    @year = params[:year].to_i
    game = Game.find(@player.game_id)
    @max_year = game.current_year-1
    @game_setting = game.game_setting
    board = Board.find(:first, :conditions=>["player_id=? AND year=?", @player.id, @year])
    @data = board.cash_flow_statement
    render :action=>"show_cash_flow_statement", :layout=>"basic_noheader_layout"
  end

  def backuppage
    db_dir = "#{RAILS_ROOT}/public/backupfiles/databases"
    @db_list = Dir.entries(db_dir)
    render :action=>"backuppage", :layout=>"basic_layout"
  end  

  def backup
    require 'zip/zip'
    db_path = "#{RAILS_ROOT}/public/backupfiles/databases"
    cmd = "mysqldump -uchaiyo -p45664566 bizdb|gzip > #{db_path}/#{Time.now.strftime('%Y_%m_%d_%H_%M_%S')}.sql.gz"
#    puts cmd
    system(cmd)
    redirect_to :action=>"backuppage"
  end

  def deletebackup3
    db_dir = "#{RAILS_ROOT}/public/backupfiles/databases"
    begin
      File.delete(db_dir+"/"+params[:filename])
    rescue
    end
    redirect_to :action=>"backuppage"
  end

  def restoredb
    db_path = "#{RAILS_ROOT}/public/backupfiles/databases"
    cmd = "gzip -d < #{db_path}/#{params[:filename]} | mysql -uchaiyo -p45664566 bizdb"
    system(cmd)
    redirect_to :action=>"backuppage"
  end

  def uploadbackup
    filename = "#{RAILS_ROOT}/public/backupfiles/databases/#{params['pfile'].original_filename.gsub(/[^a-zA-Z0-9.]/, '_')}"
    begin
      File.delete(filename)
    rescue
    end
    File.open(filename, "wb") do |f|
			f.write(params['pfile'].read)
		end
    redirect_to :action=>"backuppage"
  end

  def rawmarket
    if session[:player].player_type=="A"
      redirect_to :action=>"offer_rawmarket"
    else
      redirect_to :action=>"bid_rawmarket"
    end
  end

  def offer_rawmarket
    render :action=>"offer_rawmarket", :layout=>"basic_layout"
  end

  def bid_rawmarket
    render :action=>"bid_rawmarket", :layout=>"basic_layout"
  end

  def place_bid
    player = Player.find(session[:player].id)
    game = Game.find(player.game_id)
    price = "#{params[:price]}".to_i
    credit = "#{params[:credit]}".to_i
    quantity = ((number_with_precision(params[:quantity], :precision=>2)).to_f * 1000000).to_i
    if game.a_run_flag=='Y'
      if quantity>0
        if player.player_type=="B"
          trade = Trade.new
          trade.game_id = game.id
          trade.player_id = player.id
          trade.t_status = "Openned"
          trade.year = game.current_year
          trade.price = price
          trade.credit_term = credit
          trade.quantity = quantity
          trade.remain_quantity = quantity
          trade.bidask_flag = "B"
          trade.save
        end
      end
    end
    redirect_to :action=>"rawmarket"
  end

  def use_put_option
    player = Player.find(session[:player].id)
    game = Game.find(player.game_id)
    if game.a_run_flag=='Y'
      quantity = ((number_with_precision(params[:quantity], :precision=>2)).to_f * 1000000).to_i
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", player.id, game.current_year])
      game_error = GameError.find(:first, :conditions=>["game_id=? AND year=?", game.id, game.current_year])
      inventory_unit = pb.inventory_unit - pb.sold_unit
      placed_unit = Trade.sum(:quantity, :conditions=>["player_id=? AND year=?", player.id, game.current_year])
      if quantity>0
        if player.player_type=="A" && inventory_unit>=(placed_unit+quantity)
          if pb.put_option_remain_unit>=quantity
            account = Account.new
            account.game_id = game.id
            account.creditor_id = player.id
            account.debtor_id = 0
            account.price = game_error.put_exprice_a
            account.credit_term = 1
            account.quantity = quantity
            account.amount = quantity * game_error.put_exprice_a
            account.trade_year = game.current_year
            account.due_year = game.current_year
            account.save

            pb.ar = pb.ar + (quantity * game_error.put_exprice_a)
            pb.sold = pb.sold + (quantity * game_error.put_exprice_a)
            pb.sold_unit = pb.sold_unit + quantity
            pb.put_option_remain_unit = pb.put_option_remain_unit - quantity
            pb.save
          end
        end
      end
    end
    redirect_to :action=>"rawmarket"
  end

  def place_offer
    player = Player.find(session[:player].id)
    game = Game.find(player.game_id)
    if game.a_run_flag=='Y'
      pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", player.id, game.current_year])
      game_setting = game.game_setting
      inventory_unit = pb.inventory_unit - pb.sold_unit
      placed_unit = Trade.sum(:quantity, :conditions=>["player_id=? AND year=?", player.id, game.current_year])
      price = "#{params[:price]}".to_i
      credit = "#{params[:credit]}".to_i
      quantity = ((number_with_precision(params[:quantity], :precision=>2)).to_f * 1000000).to_i
      if quantity>0
        if player.player_type=="A" && inventory_unit>=(placed_unit+quantity)
          int_benefit = (price * (1+game_setting.level1_debt_rate)**credit) - price
          realcost = price - int_benefit
          trade = Trade.new
          trade.game_id = game.id
          trade.player_id = player.id
          trade.t_status = "Openned"
          trade.year = game.current_year
          trade.price = price
          trade.credit_term = credit
          trade.quantity = quantity
          trade.remain_quantity = quantity
          trade.bidask_flag = "A"
          trade.realcost = realcost
          if params[:direct_trade]
            if params[:direct_trade]!="0"
              trade.direct_player_id = params[:direct_trade].to_i
            end
          end
          trade.save
        end
      end
    end
    redirect_to :action=>"rawmarket"
  end

  def remove_bidoffer
    trade = Trade.find(:first, :conditions=>["player_id=? AND id=?", session[:player].id, params[:id]])
    if trade
      trade.destroy
    end
    redirect_to :action=>"rawmarket"
  end

  def accept_direct_offer
    o = Trade.find(params[:id])
    sold_unit = o.quantity

    o.fill_quantity = o.fill_quantity + sold_unit
    o.remain_quantity = o.remain_quantity - sold_unit
    o.save

    game = Game.find(o.game_id)
    if sold_unit>0
      account = Account.new
      account.game_id = game.id
      account.creditor_id = o.player_id
      account.debtor_id = o.direct_player_id
      account.price = o.price
      account.credit_term = o.credit_term
      account.quantity = sold_unit
      account.amount = sold_unit * o.price
      account.trade_year = game.current_year
      account.due_year = game.current_year + o.credit_term - 1
      account.save

      #### Add A/R A/P in player balance####
      creditor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", o.player_id, game.current_year])
      creditor_pb.ar = creditor_pb.ar + (sold_unit * o.price)
#            creditor_pb.inventory_unit = creditor_pb.inventory_unit - sold_unit
#            creditor_pb.inventory_cost = ((creditor_pb.inventory_unit * creditor_pb.inventory_unitcost)/10000.0).round * 10000
      creditor_pb.sold = creditor_pb.sold + (sold_unit * o.price)
      creditor_pb.sold_unit = creditor_pb.sold_unit + sold_unit
      creditor_pb.save
      debtor_pb = PlayerBalance.find(:first, :conditions=>["player_id=? AND year=?", o.direct_player_id, game.current_year])
      debtor_pb.ap = debtor_pb.ap + (sold_unit * o.price)
      debtor_pb.rawmat_unit = debtor_pb.rawmat_unit + sold_unit
      debtor_pb.rawmat_cost = debtor_pb.rawmat_cost + (sold_unit * o.price)
      if debtor_pb.rawmat_unit>0
        debtor_pb.rawmat_unitcost = debtor_pb.rawmat_cost.to_f/debtor_pb.rawmat_unit
      else
        debtor_pb.rawmat_unitcost = 0
      end
      debtor_pb.save
    end

    o.destroy

    redirect_to :action=>"rawmarket"
  end

  def reject_direct_offer
    trade = Trade.find(params[:id])
    if trade
      trade.destroy
    end
    redirect_to :action=>"rawmarket"
  end

end
